package com.yulang.security.handler;

import com.yulang.security.config.LoginResponseType;
import com.yulang.security.properties.CustomSpringSecurityProperties;
import com.yulang.security.result.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理认证失败的处理器 自定义响应数据类型
 */
@Component
public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private CustomSpringSecurityProperties customSpringSecurityProperties;



    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {

        if (customSpringSecurityProperties.getAuth().getLoginType().equals(LoginResponseType.JSON.name())) {
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(Result.error(e.getMessage()).toJsonString());
        }else{
            // 这里需要设置一下重定向的地址 否则会重定向到login页面 会不显示 error信息
            String referer = httpServletRequest.getHeader("Referer"); // 获取上一次请求的路径
            String s = StringUtils.substringBefore(referer, "?");
            Object toLogin = httpServletRequest.getAttribute("toLogin");
            if(toLogin!=null) {
                super.setDefaultFailureUrl(customSpringSecurityProperties.getAuth().getLoginPage()+"?error");
            }else{
                super.setDefaultFailureUrl(s+"?error");
            }
            super.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
        }

    }
}
